package www.sofn.com.config;

import cn.hutool.core.util.ObjectUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import www.sofn.com.member.MemberService;
import www.sofn.com.member.domain.po.MemberPO;

@Slf4j
@Configuration
public class DisplaySecurityConfiguration {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new PasswordEncoder() {
            @Override
            public String encode(CharSequence rawPassword) {
                return rawPassword.toString();
            }

            @Override
            public boolean matches(CharSequence rawPassword, String encodedPassword) {
                return true;
            }
        };
    }

    @Resource
    private MemberService memberService;

    @Bean
    public UserDetailsService userDetailsService()  {
        return (String openid)-> {
            final MemberPO memberPO = memberService.getMemberByOpenid(openid);
            if (ObjectUtil.isNull(memberPO)) {
                log.info("登录用户：{} 不存在.", openid);
                throw new UsernameNotFoundException("登录失败：openid 不存在");
            }
            return User.builder().username(openid).password("")
                    .authorities("member").build();
        };

    }


}
